<?php


namespace api\app\controller;


use api\app\model\AddressModel;
use api\app\validate\AddressValidate;
use cmf\controller\RestBaseController;
use think\Request;

class AddressController extends RestBaseController
{
    // 查询收货人信息
    public function indexAddress(){
        $page = input('page/d', 1);
        $pageSize = input('page_size/d', 10);
        $list = AddressModel::order('id', 'desc')
            ->field('id, name, mobile, area, address')
            ->page($page, $pageSize)
            ->select();
        $this->success('收货信息', $list);
    }

    // 添加收货地址
    public function addAddress(Request $request){
        $data = input();
        $data['id'] = $request->userId;
        $validate = new AddressValidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            return error($validate->getError());
        }
        $add = AddressModel::create($data);
        if($add){
            return success('添加成功');
        }
        return error('添加失败');
    }

    // 修改更新数据
    public function editAddress(Request $request){
        $data['id'] = $request->userId;
        $data = input('post.');
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            return error($validate->getError());
        }
        $edit = AddressModel::where('id', $data['id'])->update($data);
        if($edit){
            return success('修改成功');
        }
        return error('修改失败');
    }

    // 删除
    public function deleteAddress(Request $request){
        $data['id'] = $request->userID;
        if (!$data['id']) {
            $this->error('参数错误');
        }
        $data = input('post.');
        if (AddressModel::destroy($data['id'])) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}